package com.glory.gloryquickui.fragment

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.IdRes
import com.glory.gloryquickui.R
import com.glory.gloryquickui.base.BaseFragment
import com.glory.gloryquickui.entity.*
import com.glory.gloryquickui.view.*
import com.glory.gloryquickui.viewmodel.QuickUIViewModel
import com.glory.hiwork.mvvm.bean.ToastMessageBean
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.main.*
import org.json.JSONArray
import org.json.JSONObject

/**
 * FileName: QuickUIFragment
 * Author: XJH
 * Date: 2021/5/27 16:18
 * Description:
 * History:
 */
class QuickUIFragment(private val fromID: String) : BaseFragment<QuickUIViewModel>() {
    var controllerList = mutableListOf<ViewController<*>>()
    var controllerMapList = mutableMapOf<String, ViewController<*>>()
    var allComponents = mutableListOf<FieldBean>()
    var isDynamicTable = false //是否有动态获取表格控件
    var formQueryCondition = HashMap<String, String>() //表单查询条件
    var updateDefaultMap = HashMap<String, String>() //表格修改默认值


    override fun initData() {
        getFormJson()
        viewModel.pageJson.observe(this) {
            setPageData(it)
        }
    }

    override fun layoutId(): Int {
        return R.layout.fragment_main
    }


    private fun getFormJson() {
        viewModel.searchForm(fromID)
        if(activity?.intent?.getSerializableExtra("map") != null){
            updateDefaultMap = activity?.intent?.getSerializableExtra("map") as HashMap<String, String>
        }

//        var inputStream: InputStream? = null
//        try {
//            inputStream = applicationContext.resources.assets.open("page.txt")
//        } catch (e: IOException) {
//            e.printStackTrace()
//        }
//        val json = Utils.getString(inputStream)
//        setPageData(json)
    }

    private fun setPageData(json: String) {
        if (json.isEmpty()) {
            viewModel.defUI.toastEvent.value = ToastMessageBean("表单Json数据有误，请查验", false)
            return
        }
        val (_, _, fields) = Gson().fromJson<PageBean>(
            json,
            object : TypeToken<PageBean?>() {}.type
        )
        val fileBeanJsObject = JSONObject(json)
        val fieldsArray = fileBeanJsObject.getJSONArray("fields")
        for (i in 0 until fieldsArray.length()) {
            val configJs = fieldsArray.getJSONObject(i).getJSONObject("__config__")
            if (configJs.getString("tagIcon").equals("fieldset")) {
                viewModel.baseFormData = fields[i]
                allComponents = viewModel.baseFormData!!.config.children
                val children = configJs.getJSONArray("children")
                parsingComponents(children)
                return
            }
        }
    }

    private fun parsingComponents(fieldsArray: JSONArray) {
        val map = HashMap<String, String>()
        for (i in 0 until fieldsArray.length()) {
            val configJs = fieldsArray.getJSONObject(i).getJSONObject("__config__")
            if (configJs.getString("tagIcon").equals("table") && configJs.getString("dataType")
                    .equals("manual")
            ) {
                val dataArray = try {
                    fieldsArray.getJSONObject(i).getJSONArray("data")
                } catch (e: Exception) {
                    continue
                }

                val totalLineList = arrayListOf<ArrayList<TableCustomBean>>()
                val totalPortraitList = arrayListOf<TablePortraitBaseCustomBean>()
                for (j in 0 until dataArray.length()) {
                    val dataJs = dataArray.getJSONObject(j)
                    val lineList = arrayListOf<TableCustomBean>()
                    val baseBean = TablePortraitBaseCustomBean()
                    val PortraitList = arrayListOf<TablePortraitCustomBean>()
                    allComponents[i].config.children.forEach { item ->
                        val tableBean = TableCustomBean()
                        val tablePortraitBean = TablePortraitCustomBean(false)
                        if (item.prop == "s_index") {
                            tableBean.textName = i.toString()
                            tablePortraitBean.textName = "序号"
                            tablePortraitBean.textValue = i.toString()
                        } else {
                            if (dataJs.isNull(item.prop)) {
                                tableBean.textName = ""
                                tablePortraitBean.textProp = item.prop
                                tablePortraitBean.textName = item.label
                                tablePortraitBean.textValue = ""
                            } else {
                                tableBean.textName = dataJs.getString(item.prop)
                                tablePortraitBean.textName = item.label
                                tablePortraitBean.textValue = dataJs.getString(item.prop)
                                tablePortraitBean.textProp = item.prop
                            }
                        }
                        lineList.add(tableBean)
                        PortraitList.add(tablePortraitBean)
                    }
                    totalLineList.add(lineList)
                    baseBean.ID = ""
                    baseBean.tablelineData = PortraitList
                    totalPortraitList.add(baseBean)
                }
                allComponents[i].tablelineData = totalLineList
                allComponents[i].tablePortraitData = totalPortraitList

            } else if (configJs.getString("tagIcon")
                    .equals("table") && configJs.getString("dataType")
                    .equals("dataTable")
            ) {
                isDynamicTable = true
                viewModel.dynamicComponents.add(allComponents[i])
            } else if (configJs.getString("tagIcon")
                    .equals("table") && configJs.getString("dataType")
                    .equals("third")
            ){
                isDynamicTable = true
                viewModel.dynamicComponents.add(allComponents[i])
            }else if (configJs.getString("tagIcon").equals("input")){
                if(allComponents[i].slot.prepend.equals("1")){
                    formQueryCondition.put(allComponents[i].vModel,"")
                }
            }
        }
        viewModel.baseFormData?.formQueryCondition = formQueryCondition //表单请求参数

        //判断外层表单是否需要查询
        if(  viewModel.baseFormData?.config?.dataSourceTable != null &&   viewModel.baseFormData?.config?.dataSourceTable!!.size != 0){
            viewModel.dynamicComponents.add(  viewModel.baseFormData!!) //需要请求的集合
        }
        allComponents.forEach {
            if(updateDefaultMap.containsKey(it.vModel)){
                it.config.defaultValue = updateDefaultMap.get(it.vModel)
            }
        }

        allComponents.forEach { data ->

            if (data.config.defaultValue is String) {
                map[data.vModel] = data.config.defaultValue.toString()
            } else {
                if (data.vModel.isNotEmpty()){
                    map[data.vModel] = ""
                }
            }
            viewModel.pageData.value = map
            when (data.config.tagIcon) {
                "input" -> {//单行输入框
                    val vc = SingleEditTextController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    if (data.readonly) {
                        viewModel.pageData.observe(this) {
                            (vc.masterPart() as EditText).setText(it[data.vModel])
                        }
                    }
                }
                "textarea" -> {//多行输入框
                    val vc = ManyEditTextController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    if (data.readonly) {
                        viewModel.pageData.observe(this) {
                            (vc.masterPart() as EditText).setText(it[data.vModel])
                        }
                    }
                }
                "password" -> {//密码输入框
                    val vc = PasswordEditTextController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    if (data.readonly) {
                        viewModel.pageData.observe(this) {
                            (vc.masterPart() as EditText).setText(it[data.vModel])
                        }
                    }
                }
                "number" -> {//计数器
                    val vc = CounterTextController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    viewModel.pageData.observe(this) {
                        (vc.masterPart() as TextView).text = it[data.vModel]
                    }
                }
                "select" -> {//下拉选择
                    val vc = DropDowmSelectController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    viewModel.pageData.observe(this) {
                        (vc.masterPart() as TextView).text = it[data.vModel]
                    }
                }
                "radio" -> {//单选框
                    val vc = RadioButtonSelectController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                }
                "checkbox" -> {//多选框
                    val vc = CheckBoxSelectController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                }
                "cascader" -> {//级联选择
                    val vc = CascadeViewController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    viewModel.pageData.observe(this) {
                        (vc.masterPart() as TextView).text = it[data.vModel]
                    }
                }
                "switch" -> {//开关按钮
                    val vc = ToggleButtonController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                }
                "slider" -> {//滑块
                    val vc = SeekViewController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                }
                "date" -> {//日期选择
                    val vc = DateChooseController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    viewModel.pageData.observe(this) {
                        (vc.masterPart() as TextView).text = it[data.vModel]
                    }
                }
                "date-range" -> {//日期区间选择
                    val vc = DateRangeChooseController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                }
                "rate" -> {//评分控件
                    val vc = RattingBarController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                }
                "button" -> {//普通按钮
                    val vc = ButtonController(activity)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    vc.masterPart()!!.setOnClickListener {
                        setEvent(data)
                    }
                }
                "table" -> {//表格
                    val vc = TablePortraitViewController(activity,viewModel)
                    vc.attachRoot(llContainer)
                    vc.fillData(data)
                    controllerList.add(vc as ViewController<*>)
                    controllerMapList[data.config.formId] = vc
                    viewModel.pageData.observe(this) {
                        if(it[data.vModel]!!.isNotEmpty()){
                            vc.update(it[data.vModel])
                        }
                    }
                    viewModel.defUI.callObserve.observe(this){
                        vc.removeData(it.item as Int)
                    }
                }
                "row" -> {//行容器
                    if(data.type.equals("flex")){
                        val vc = RowViewController(activity,viewModel)
                        vc.attachRoot(llContainer)
                        vc.fillData(data)
                        controllerList.add(vc as ViewController<*>)
                        controllerMapList[data.config.formId] = vc
                    }
                }
            }
        }

        //是否首次请求
        if(  viewModel.baseFormData?.formQueryCondition == null ||   viewModel.baseFormData?.formQueryCondition!!.size == 0){
            viewModel.searchData()
        }

    }

    private fun setEvent(data: FieldBean) {
        when (data.config.eventType) {
            "manual" -> {
                if (data.config.eventName == "saveForm") {
                    viewModel.saveData()
                } else if (data.config.eventName == "clearForm") {
                    viewModel.searchData()
                } else if (data.config.eventName == "backPage") {
                } else if (data.config.eventName.contains("get")) {
                    viewModel.searchData()
                } else if (data.config.eventName.contains("delete")) {

                }
            }
            "interface" -> {

            }
            "froms" -> {

            }
            "pageInteraction" -> {

            }
        }
    }

    fun getMasterPart(position: Int): View? {
        return controllerList[position].masterPart()
    }

    fun getMasterPart(formId: String): View? {
        return controllerMapList[formId]?.masterPart()
    }

    fun setOnClickListen(position: Int, onClick: View.OnClickListener) {
        if (controllerList[position].masterPart() != null) {
            controllerList[position].masterPart()!!.setOnClickListener(onClick)
        }
    }

    fun setOnClickListen(formId: String, onClick: View.OnClickListener) {
        if (controllerMapList[formId]?.masterPart() != null) {
            controllerMapList[formId]?.masterPart()!!.setOnClickListener(onClick)
        }
    }

    fun setOnLongClickListen(formId: String, onClick: View.OnLongClickListener) {
        if (controllerMapList[formId]?.masterPart() != null) {
            controllerMapList[formId]?.masterPart()!!.setOnLongClickListener(onClick)
        }
    }

    private fun <T : View> getView(@IdRes viewId: Int): T {
        val view = controllerList[viewId]
        return view as T
    }

    override fun initView(savedInstanceState: Bundle?) {
    }
}